package com.test.platform.module.system.service;

import com.test.platform.component.GitComponent;
import com.test.common.component.RedisComponent;
import com.test.common.entity.system.User;
import com.test.common.repository.system.UserRepository;
import com.test.common.response.BizException;
import com.test.common.utils.ExecutorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.Permission;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Slf4j
@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private RedisComponent redisCommonUtil;

    @Resource
    private GitComponent component;

    public User create(User user) {

        // 先保存用户
        try {
            user = userRepository.save(user);
            redisCommonUtil.set("shiro:user:" + user.getId(), user);
        } catch (Exception e) {
            log.error("创建用户失败");
            e.printStackTrace();
            throw new BizException("创建用户失败", e);
        }

        final User tmpUser = user;

        ExecutorUtils.execute(() -> {
            // 创建这个用户的自动化脚本分支
            if (component.autotestScriptInit(tmpUser.getName())) {
                log.info("创建用户，初始化仓库成功");
            } else {
                log.error("创建用户，初始化仓库失败");
            }
        });

        return user;
    }

    public Page<User> findAll(int page, int size) {
        return userRepository.findAll(PageRequest.of(page, size, Sort.by("id")));
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public User findByName(String name) {
        return userRepository.findByName(name);
    }

    public User findById(Integer id) {

        User user = redisCommonUtil.get("shiro:user:" + id, User.class);
        if (user != null) {
            return user;
        } else {
            Optional<User> optional = userRepository.findById(id);
            if (optional.isPresent()) {
                user = optional.get();
                user.initPermissionsAll();
                redisCommonUtil.set("shiro:user:" + id, user, 60);
                return user;
            } else {
                throw new BizException("用户不存在：" + id);
            }
        }
    }

    public Set<Permission> findPermissions(Integer userId) {
        return findById(userId).getPermissionsAll();
    }

    public User update(User user) {
        user = userRepository.save(user);
        redisCommonUtil.set("shiro:user:" + user.getId(), user);
        return user;
    }

    public String delete(Integer id) {
        redisCommonUtil.delete("shiro:user:" + id);
        userRepository.deleteById(id);
        return "删除成功";
    }

    public User currentUser() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }
}
